package jbl.action;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import jbl.io.excel.ExportExcel;
import jbl.io.excel.LogExcel;
import jbl.pageModel.Log;
import jbl.service.LogServiceI;
import jbl.util.Json;
import jbl.util.Message;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;
/**
 * 
 * @author jblcxg
 * 
 * 登录日志管理 记录用户信息  地址 登录状态
 *
 */
@Namespace("/")
@Action(value="logAction")
public class LogAction extends BaseAction implements ModelDriven<Log>{
	private Log log = new Log();
	
	private LogServiceI logService;
	
	@Autowired
	public void setLogService(LogServiceI logService) {
		this.logService = logService;
	}

	@Override
	public Log getModel() {
		return log;
	}
	/**
	 * 返回日志DataGrid
	 */
	public void dataGrid(){
		writeJson(logService.dataGrid(log));
	}
	/**
	 * 下载日志excel文件
	 **/
	public void exporLogExcel(){
			Json j = new Json();
			HttpServletResponse response = ServletActionContext.getResponse();
			try {
				
				List<LogExcel> dataset = logService.getLogList(log);
				if(dataset != null &&dataset.size() > 0){
					String[] hearders = new String[] {Message.XH,Message.ZH, Message.IP, Message.LOG, Message.SJ};//表头数组
	
					ExportExcel<LogExcel> ex = new ExportExcel<LogExcel>();
					
					String filename = Message.dateFormat.format(new Date())+Message.LOG_EXCEL_NAME+".xls";
					response.setContentType("application/ms-excel;charset=UTF-8");
					try {
						//response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(filename, "UTF-8"))));
						response.setHeader("Content-disposition","attachment; filename="+    new String(filename.getBytes("gb2312"), "ISO8859-1"));//filename是下载的xls的名，建议最好用英文
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
						j.setMsg("导出失败， 编码错误!");
						writeJson(j);
					}
					OutputStream out = response.getOutputStream();
			        ex.exportExcel(Message.LOG_EXCEL_NAME,hearders, dataset, out,Message.FORMAT_TIME);
			        out.close();
				}else{
					j.setMsg("导出失败， 数据为空!");
					writeJson(j);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				j.setMsg("导出失败!");
				writeJson(j);
			}

	}
}
